<template>
  <div class="doctor-management">
    <div class="header">
      <h2>医生管理</h2>
      <el-button v-if="isAdmin" type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                添加医生
              </el-button>
            </div>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="医生姓名、工号"
            clearable
            @clear="handleSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="科室">
          <el-tree-select
            v-model="searchForm.departmentId"
            placeholder="请选择科室"
            clearable
            filterable
            :data="departmentTree"
            node-key="id"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children'
            }"
            check-strictly
          />
        </el-form-item>
        <!-- <el-form-item label="职称">
          <el-select v-model="searchForm.title" placeholder="请选择职称" filterable clearable>
            <el-option label="全部" value="" />
            <el-option label="主任医师" :value="1" />
            <el-option label="副主任医师" :value="2" />
            <el-option label="主治医师" :value="3" />
            <el-option label="住院医师" :value="4" />
            <el-option label="实习医师" :value="5" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" filterable clearable>
            <el-option label="全部" value="" />
            <el-option label="在职" :value="1" />
            <el-option label="离职" :value="0" />
            <el-option label="休假" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="statistics" v-if="isAdmin">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.total }}</div>
            <div class="stat-label">总医生数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.active }}</div>
            <div class="stat-label">在职医生</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.senior }}</div>
            <div class="stat-label">高级职称</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statistics.departments }}</div>
            <div class="stat-label">科室数量</div>
          </div>
      </el-col>
    </el-row>
    </div>

    <!-- 医生列表 -->
    <el-table
      :data="tableData"
      v-loading="loading"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column prop="doctorNo" label="工号" width="120" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="departmentName" label="科室" width="120" />
      <el-table-column prop="title" label="职称" width="120">
      </el-table-column>
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          {{ getGenderText(row.gender) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="130" />
      <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
      <el-table-column prop="workYears" label="工作年限" width="100">
        <template #default="{ row }">
          {{ row.workYears }}年
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="specialty" label="专长" min-width="150" show-overflow-tooltip />
      <el-table-column v-if="isAdmin" label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            <el-icon><View /></el-icon>
            详情
          </el-button>
          <el-button type="success" size="small" @click="handleEdit(row)">
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="warning"
            size="small"
            @click="handleUpdateStatus(row, 0)"
          >
            离职
          </el-button>
          <el-button
            v-else-if="row.status === 0"
            type="info"
            size="small"
            @click="handleUpdateStatus(row, 1)"
          >
            复职
          </el-button>
          <el-button
            v-if="row.status === 1"
            type="danger"
            size="small"
            @click="handleUpdateStatus(row, 2)"
          >
            休假
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, View, Edit } from '@element-plus/icons-vue'
import { getDoctors, getDoctorDetail, addDoctor, updateDoctor, deleteDoctor } from '@/api/admin'
import { getDepartmentTree } from '@/api/business'
import { addDialog } from '@/components/gDialog/index'
import doctorHandle from '@/views/adminModal/doctorHandle.vue'
import doctorDetailHandle from '@/views/adminModal/doctorDetailHandle.vue'
import { useUserStore } from '@/stores/user'
// 响应式数据
const loading = ref(false)
const departmentTree = ref([])
const doctorList = ref([])
const userStore = useUserStore()
const isAdmin = computed(() => userStore.isAdmin)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  departmentId: null,
  title: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})
const tableData = ref([])

// 统计数据
const statistics = computed(() => {
  const total = tableData.value.length
  const active = tableData.value.filter(item => item.status === 1).length
  const senior = tableData.value.filter(item => item.title === 1 || item.title === 2).length
  const departments = new Set(tableData.value.map(item => item.departmentId)).size
  
  return { total, active, senior, departments }
})

// 页面加载时获取数据
onMounted(() => {
  fetchDoctors()
  fetchDepartmentTree()
})

// 获取医生列表
const fetchDoctors = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getDoctors(params)
    
    if (response.code === 200) {
      const doctors = response.data.list || []
      await fillDepartmentNames(doctors)
      tableData.value = doctors
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取医生列表失败')
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败')
  } finally {
    loading.value = false
  }
}

// 获取科室树形数据
const fetchDepartmentTree = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    } else {
      ElMessage.error(response.message || '获取科室树形数据失败')
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
    ElMessage.error('获取科室树形数据失败')
  }
}

// 填充科室名称
const fillDepartmentNames = async (doctors) => {
  if (!doctors || doctors.length === 0) return
  
  const findDepartment = (list, id) => {
    for (const item of list) {
      if (item.id === id) {
        return item
      }
      if (item.children) {
        const found = findDepartment(item.children, id)
        if (found) {
          return found
        }
      }
    }
    return null
  }
  
  // doctors.forEach(doctor => {
  //   if (doctor.departmentId) {
  //     const department = findDepartment(departmentTree.value, doctor.departmentId)
  //     if (department) {
  //       doctor.departmentName = department.name
  //     }
  //   }
  // })
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchDoctors()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    departmentId: null,
    title: '',
    status: ''
  })
  pagination.page = 1
  fetchDoctors()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchDoctors()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchDoctors()
}

// 添加医生
const handleAdd = () => {
  console.log(departmentTree.value,'departmentTree.value')
  addDialog({
    title: '添加医生',
    component: doctorHandle,
    width: '800px',
    props: {
      doctorData: {},
      isEdit: false,
      departmentTree: departmentTree.value
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchDoctors()
      }
    }
  })
}

// 编辑医生
const handleEdit = (row) => {
  addDialog({
    title: '编辑医生',
    component: doctorHandle,
    width: '800px',
    props: {
      doctorData: row,
      isEdit: true,
      departmentTree: departmentTree.value
    },
    callBack: (result) => {
      if (result === 'success') {
        fetchDoctors()
      }
    }
  })
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getDoctorDetail(row.id)
    if (response.code === 200) {
      addDialog({
        title: '医生详情',
        component: doctorDetailHandle,
        width: '700px',
        props: {
          doctorData: response.data
        }
      })
    } else {
      ElMessage.error(response.message || '获取医生详情失败')
    }
  } catch (error) {
    console.error('获取医生详情失败:', error)
    ElMessage.error('获取医生详情失败')
  }
}

// 更新状态
const handleUpdateStatus = async (row, newStatus) => {
  const statusText = getStatusText(newStatus)
  
  try {
    await ElMessageBox.confirm(
      `确定要将医生"${row.name}"设置为${statusText}吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await updateDoctor({
      ...row,
      status: newStatus
    })

    if (response.code === 200) {
      ElMessage.success(`医生状态更新为${statusText}成功`)
      fetchDoctors()
    } else {
      ElMessage.error(response.message || '状态更新失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('状态更新失败:', error)
      ElMessage.error('状态更新失败')
    }
  }
}

// 获取性别文本
const getGenderText = (gender) => {
  const genderMap = {
    0: '未知',
    1: '男',
    2: '女'
  }
  return genderMap[gender] || '未知'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '离职',
    1: '在职',
    2: '休假'
  }
  return statusMap[status] || '未知'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'success',
    2: 'warning'
  }
  return typeMap[status] || 'info'
}

// 获取职称文本
const getTitleText = (title) => {
  const titleMap = {
    1: '主任医师',
    2: '副主任医师',
    3: '主治医师',
    4: '住院医师',
    5: '实习医师'
  }
  return titleMap[title] || '未知'
}

// 获取职称标签类型
const getTitleTagType = (title) => {
  const typeMap = {
    1: 'danger',   // 主任医师 - 红色
    2: 'warning',  // 副主任医师 - 橙色
    3: 'primary',  // 主治医师 - 蓝色
    4: 'success',  // 住院医师 - 绿色
    5: 'info'      // 实习医师 - 灰色
  }
  return typeMap[title] || 'info'
}
</script>

<style scoped>
.doctor-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-form-item__label) {
  font-weight: 600;
}
</style> 